package com.voucher.qiege.one;

import org.apache.http.client.CookieStore;

import javax.crypto.Cipher;
import javax.crypto.spec.*;
import java.util.Base64;
import java.util.Map;
import java.util.HashMap;

public class PasswordEncryptor {

    public static String encrypt(String password, CookieStore cookieStore) throws Exception {
        // 从CookieStore中提取JSESSIONID
        String jsessionId = cookieStore.getCookies().stream()
                .filter(c -> "JSESSIONID".equals(c.getName()))
                .findFirst()
                .map(org.apache.http.cookie.Cookie::getValue)
                .orElseThrow(() -> new RuntimeException("JSESSIONID未找到"));

        Map<String, String> keys = generateKeys(jsessionId);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(
            keys.get("key").getBytes("UTF-8"), 
            "AES"
        );
        IvParameterSpec ivSpec = new IvParameterSpec(
            keys.get("iv").getBytes("UTF-8")
        );
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(password.getBytes("UTF-8"));
        return keys.get("security") + Base64.getEncoder().encodeToString(encrypted);
    }

    private static Map<String, String> generateKeys(String sessionId) {
        String keyMaterial = (sessionId + "abcdefghijklmnopqrstuvwxyz1234567890")
                .substring(0, 32)
                .toUpperCase();
        return new HashMap<String, String>() {{
            put("security", "\u4435\u5320\u4d35"); // Unicode字符: 匵㌠䴵
            put("key", keyMaterial.substring(0, 16));
            put("iv", keyMaterial.substring(16, 32));
        }};
    }
}
